﻿using System;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace EcoSystem.Contributor
{

    /// <summary>
    /// 脚本引擎注册动态脚本函数处理初台化程序
    /// </summary>
    public class ScriptEngineContributor : IDataSeedContributor, ITransientDependency
    {
        private readonly IReadOnlyRepository<HttpApiConfig, Guid> httpApiRepository;
        private readonly IScriptAppService ScriptAppService;

        public ScriptEngineContributor(
            IReadOnlyRepository<HttpApiConfig, Guid> httpApiRepository,
            IScriptAppService scriptAppService)
        {
            this.httpApiRepository = httpApiRepository;
            ScriptAppService = scriptAppService;
        }

        public async Task SeedAsync(DataSeedContext context)
        {
            await RegisterHttpApiScriptMethods();
        }

        /// <summary>
        /// 注册API接口动态脚本函数
        /// </summary>
        /// <returns></returns>
        private async Task RegisterHttpApiScriptMethods()
        {
            var query = (await httpApiRepository.GetQueryableAsync()).Where(x => x.Status == true);
            var items = await query.Select(x => new { x.Code, x.ScriptContent }).ToListAsync();
            foreach (var item in items)
            {
                string methodName = $"$method_httpapi_{item.Code}";
                var content = item.ScriptContent ?? "return '';";
                ScriptAppService.RegisterMethod(methodName, content, new string[] { "$params" });
            }
        }
    }
}
